<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 表头 全局注册 -->
      <page-tools :show-before="true">
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <!-- 对于按钮的点击权限(type=2 第二级的权限)
          1. 权限表
          2. 给当前按钮命名
          3. 进行判断, 如果这个按钮名字在权限表中存在则允许点击, 如果没有则不让点击 -->
          <el-button :disabled="!checkPermission('EMPLOYEE-ADD')" size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <!-- 表格组件 -->
        <el-table border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <!-- 图像 -->
          <el-table-column label="图像">
            <template slot-scope="scope">
              <img v-imgError="require('@/assets/common/soccer.jpg')" class="staffPhoto" :src="scope.row.staffPhoto" @click="showCodeDialog(scope.row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column
            label="聘用形式"
            sortable=""
            prop="formOfEmployment"
            :formatter="formatEmployment"
          />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="">
            <template slot-scope="scope">
              <!-- 全局过滤器格式化事件 -->
              {{ scope.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column
            label="账户状态"
            sortable=""
            prop="enableState"
          >
            <!-- 拆分v-model,只显示，所以使用value -->
            <template slot-scope="scope">
              <el-switch
                :value="scope.row.enableState===1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${scope.row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(scope.row.id)">角色</el-button>
              <el-button type="text" size="small" @click="deleteEmployee(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :page-sizes="[10, 20, 30, 40]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @current-change="currentChange"
            @size-change="sizeChange"
          />
        </el-row>
      </el-card>
      <!-- 新增员工弹层 -->
      <addEmployee :show-dialog.sync="showDialog" @getEmployeeList="getEmployeeList" />
      <!-- 角色分配弹层 -->
      <assignRole ref="assignRole" :is-show-role.sync="isShowRole" :user-id="userId" />
      <!-- 二维码 -->
      <el-dialog title="二维码" :visible="isShowCode" @close="isShowCode = false">
        <el-row type="flex" justify="center" align="middle">
          <canvas ref="mycanvas" />
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import QRcode from 'qrcode'
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import addEmployee from '@/views/employees/components/add-employee'
import assignRole from '@/views/employees/components/assign-role'
// 过滤器在js中无法使用,解决方法：单独引入，当普通函数使用
import { formatDate } from '@/filters'
export default {
  components: {
    addEmployee, assignRole
  },
  data() {
    return {
      list: [],
      total: 0,
      page: {
        page: 1,
        size: 10
      },
      userId: '',
      // 弹窗使用的数据
      showDialog: false,
      isShowCode: false,
      isShowRole: false
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.page)
      // console.log(rows)
      this.list = rows
      this.total = total
    },
    currentChange(newPage) {
      this.page.page = newPage
      this.getEmployeeList()
    },
    sizeChange(newSize) {
      this.page.size = newSize
      this.getEmployeeList()
    },
    // 格式化文档
    formatEmployment(row, column, cellValue, index) {
      // console.log(row, column, cellValue, index)
      // 格式化函数拦截了当前单元格的渲染,这里可以运行逻辑,然后return结果
      let res = '未知'
      EmployeeEnum.hireType.forEach((item) => {
        // console.log(item)
        if (item.id === cellValue) {
          res = item.value
        }
      })
      return res
    },
    // 员工删除方法
    async deleteEmployee(id) {
      try {
        // 二次确认
        await this.$confirm('确认删除该角色？')
        await delEmployee(id)
        await this.getEmployeeList()
        this.$message.success('操作成功')
      } catch (error) {
        console.log(error)
      }
    },
    async exportExcel() {
      // 导出员工数据
      // 1、获取员工数据
      const { rows } = await getEmployeeList({ page: 1, size: this.total })
      // console.log(rows)
      // 2、根据需要转换数据
      // 需要字典
      const headersDict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const arr = rows.map(item => {
        return this.obj2array(item, headersDict)
      })
      // 3、使用插件生成文件，输出给用户
      // 3.1 按需引入插件
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: Object.keys(headersDict), // 表头 必填
          data: arr, // 具体数据 必填
          filename: 'excel-list', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
      // 3.2 自动生成文件
    },
    obj2array(item, headersDict) {
      const arr = []
      for (const key in headersDict) {
        const enKey = headersDict[key]
        // 处理日期时间
        if (headersDict[key] === 'timeOfEntry' || headersDict[key] === 'correctionTime') {
          arr.push(formatDate(item[enKey], 'yyyy/MM/dd'))
        } else {
          arr.push(item[enKey])
        }
      }
      return arr
    },
    showCodeDialog(imgUrl) {
      console.log(imgUrl)
      console.log('clickk')
      this.a = 1
      if (imgUrl) {
        this.isShowCode = true
      }
      this.$nextTick(() => {
        QRcode.toCanvas(this.$refs.mycanvas, imgUrl)
      })
    },
    // 角色编辑
    async editRole(id) {
      this.userId = id
      await this.$refs.assignRole.getUserDetailById(id) // 父组件调用子组件方法
      this.isShowRole = true
    }
  }
}
</script>

<style lang="scss" scoped>
.staffPhoto{
  width: 100px;
  height: 100px;
  object-fit: cover;
}
</style>>

